package com.example.firstdemo.ui.screens.components

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import coil3.compose.AsyncImagePainter
import coil3.compose.rememberAsyncImagePainter
import coil3.request.ImageRequest
import com.example.firstdemo.R
import com.example.firstdemo.ui.theme.AppTheme

class ZoomableImageState1() {
    var isShow by mutableStateOf(true)
        private set
    var imageUrl by mutableStateOf<String?>(null)
        private set
    var scale by mutableFloatStateOf(1f)
        private set
    var offset by mutableStateOf(Offset.Zero)
        private set

    var containerSize = IntSize(0, 0)
    var imageOriginSize = IntSize(0, 0)

    private fun calculateOffset(imageSize: IntSize, tapOffset: Offset): Offset {
        // 计算双击点在放大后坐标系中的位置
        val scaledTapX = tapOffset.x * scale
        val scaledTapY = tapOffset.y * scale

        // 计算容器的中心点
        val centerX = imageSize.width / 2
        val centerY = imageSize.height / 2

        // 计算需要的偏移量，使双击点位于中心
        var offsetX = centerX - scaledTapX
        var offsetY = centerY - scaledTapY

        // 计算放大后的图片尺寸
//        val scaledWidth = containerSize.width * scale
//        val scaledHeight = containerSize.height * scale

//        val moveableX = (scaledWidth - containerSize.width) / 2
//        val moveableY = (scaledHeight - containerSize.height) / 2
//
//        // 限制偏移量，防止图片超出边界
//        offsetX = offsetX.coerceIn(-moveableX, moveableX)
//        offsetY = offsetY.coerceIn(-moveableY, moveableY)

        return Offset(offsetX, offsetY)
    }

    fun doubleTapZoom(
        imageSize: IntSize,
        containerSize: IntSize,
        imageOriginSize: IntSize,
        tapOffset: Offset
    ) {
        this.containerSize = containerSize
        this.imageOriginSize = imageOriginSize
        if (scale == 1f) {
            this.scale = imageOriginSize.width.toFloat() / containerSize.width
            this.offset = calculateOffset(imageSize, tapOffset)
        } else {
            resetTransform()
        }
    }

    fun resetTransform() {
        scale = 1f
        offset = Offset.Zero
    }

    fun updateScale(scale: Float) {
        this.scale = scale
    }

    fun updateOffset(offset: Offset) {
        this.offset = offset
    }

    fun open(imageUrl: String) {
        this.imageUrl = imageUrl
        isShow = true
    }

    fun close() {
        imageUrl = null
        isShow = false
    }
}


@Composable
fun ZoomableImage() {
    val context = LocalContext.current
    val state = remember { ZoomableImageState1() }

    var loaded by remember { mutableStateOf(false) }
    var imageOriginalSize by remember { mutableStateOf<IntSize?>(null) }

    val painter = rememberAsyncImagePainter(
//        model = "https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg",
        model = ImageRequest.Builder(context)
            .data(R.drawable.pic)
            .size(coil3.size.Size.ORIGINAL) // 请求原始尺寸
            .build(),
        onState = { state ->
            if (state is AsyncImagePainter.State.Success) {
                loaded = true
                val image = state.result.image
                imageOriginalSize = IntSize(image.width, image.height)
            } else {
                loaded = false
            }
        }
    )

    // 全屏图片（带缩放手势）
    AnimatedVisibility(
        visible = state.isShow && loaded,
        enter = fadeIn(),
        exit = fadeOut()
    ) {
        var containerSize by remember { mutableStateOf(IntSize.Zero) }
        Box(
            contentAlignment = Alignment.Center,
            modifier = Modifier
                .size(300.dp)
                .border(1.dp, Color.Red)
                .background(Color.Black.copy(alpha = 0.6f))
                .onGloballyPositioned { coordinates ->
                    containerSize = coordinates.size
                }
                .pointerInput(Unit) {
                    detectTapGestures(
//                        onTap = { state.close() }
                    )
                }
        ) {
            Image(
                painter = painter,
                contentDescription = null,
                contentScale = ContentScale.Fit,
                modifier = Modifier
                    .graphicsLayer(
                        scaleX = state.scale,
                        scaleY = state.scale,
                        translationX = state.offset.x,
                        translationY = state.offset.y,
                        transformOrigin = TransformOrigin(0f, 0f)
                    )
//                    .scale(state.scale, state.scale)
//                    .offset {
//                        IntOffset(
//                            state.offset.x.roundToInt(),
//                            state.offset.y.roundToInt()
//                        )
//                    }
                    .pointerInput(Unit) {
                        detectTapGestures(
                            onDoubleTap = { tapOffset ->
                                state.doubleTapZoom(
                                    size,
                                    containerSize,
                                    imageOriginalSize!!,
                                    tapOffset
                                )
                            },
                        )
                    }
                    .pointerInput(Unit) {
                        detectTransformGestures { _, pan, zoom, _ ->
                            state.apply {
                                updateScale(scale * zoom)
                                updateOffset(
                                    Offset(
                                        x = offset.x + pan.x * scale,
                                        y = offset.y + pan.y * scale
                                    )
                                )
                            }
                        }
                    }
//                    .pointerInput(Unit) {
//                        detectTapGestures(
//                            onDoubleTap = { tapOffset ->
//                                state.doubleTapZoom(containerSize, imageOriginalSize!!, tapOffset)
//                            }
//                        )
//                    }
            )
            Box(
                Modifier
                    .size(10.dp)
                    .background(Color.Red, CircleShape)
            )
        }
    }

}


//@Composable
//fun ImageWithOriginalSize(url: String) {
//    var originalSize by remember { mutableStateOf<IntSize?>(null) }
//    val painter = rememberAsyncImagePainter(
//        model = url,
//        onState = { state ->
//            if (state is AsyncImagePainter.State.Success) {
//                val imageBitmap = state.result.drawable.toBitmap()
//                originalSize = IntSize(imageBitmap.width, imageBitmap.height)
//            }
//        }
//    )
//    LaunchedEffect(originalSize) {
//        originalSize?.let {
//            Log.d("ImageSize", "Original size: ${it.width} x ${it.height}")
//        }
//    }
//
//    Image(
//        painter = painter,
//        contentDescription = null,
//        contentScale = ContentScale.Fit
//    )
//}


@Preview(
    showSystemUi = true
)
@Composable
fun ZoomableImagePreview2() {
    AppTheme {
        Surface {
            ZoomableImage()
        }
    }
}